#include "telbook.h"

void read_entry(char *str[])
{ 
  char read_name[SUBSIZE];
  char read_number[SUBSIZE];
  int index = atoi(str[3]);
  if(index < 1)
  {
   printf("Invalid index\n");
   exit(0);
  }
  int fd;
  char action_buffer[40];
  off_t offset;
  //open file for reading
  if((fd = open(str[2],O_RDONLY,PERMS)) < 0)
    {
     perror("Could not open file:");
     exit(0);
    }
  //call write_log to log open action
  sprintf(action_buffer,"%s %s","Opened File:",str[2]);
  write_log(action_buffer);
  
  // check if index exceeds file size
  if((lseek(fd,0,SEEK_END))<(index)*SIZE)
   {
    printf("Index too large!\n");
    exit(0);
   }
  if ((offset=(lseek(fd,(index-1)*SIZE , SEEK_SET))) == -1)
    {
     perror("Could not seek in file:");
     exit(0);
    }
  if((read(fd,read_name,SUBSIZE))!=SUBSIZE)
    {
     perror("Failed to read:");
     exit(0);
    }
 //check if no entry at specified index
  if(read_name[0] == '\0')
   { 
    printf("No Entry Here!\n");
    exit(0);
   }
  else 
   printf("name: %s  ",read_name);
  if((lseek(fd, (index-1)*SIZE+SUBSIZE, SEEK_SET)) == -1)
    {
     perror("Failed to seek in file:");
     exit(0);
    }
  if((read(fd,read_number,SUBSIZE))!=SUBSIZE)
    {
     perror("Failed to read:");
     exit(0);
    }

  printf("phone number: %s \n",read_number);
  //create and write content log 
  sprintf(action_buffer,"%s %d %s %d","Read Content:",SIZE,"bytes starting from position ",offset);
  write_log(action_buffer);
  close(fd);
  //create and write close log
  sprintf(action_buffer,"%s %s","Closed File:",str[2]);
  write_log(action_buffer);

}
